<template>
    <div class="publish-Purchase">
        <el-form ref="formRef" :model="form" :rules="formRules" label-position="top">
            <el-card>
                <span class="_before">基本信息</span>
                <el-form-item label="购箱城市" prop="boxStartCity"  required style="width: 300px;margin-top: 30px;">
                    <city-select ref="startCityRef" v-model="form.boxStartCity" :needInfo="true"  :disabled="isInfo" :cityList="startCityList"  @cityId="startCityInfo" style="width: 100%;"></city-select>
                </el-form-item>
                <el-form-item label="求购箱属性" prop="boxStyle">
                    <boxPriceList ref="boxPriceListRef" :isSell="true" :priceList="form.priceList" :disabled="isInfo" @currency="publishCurrency"></boxPriceList>
                </el-form-item>
                <el-form-item label="可结算币种" prop="payCurrency">
                    <el-checkbox-group v-model="form.payCurrency">
                        <el-checkbox label="人民币（CNY）" value="CNY" :disabled="form.isCheckCNY || isInfo"/>
                        <el-checkbox label="美元（USD）" value="USD"  :disabled="form.isCheckUSD || isInfo"/>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="发票类型" prop="invoiceType">
                    <el-checkbox-group v-model="form.invoiceType" :disabled="isInfo">
                        <el-checkbox label="增值税普通发票" value="5" />
                        <el-checkbox label="增值税专用发票" value="10" />
                        <el-checkbox label="形式发票" value="15" />
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="预计提箱日期"  prop="planPickupDate">
                    <el-date-picker v-model="form.planPickupDate" :disabled="isInfo" type="date" placeholder="" :disabled-date="disabledDate"/>
                </el-form-item>
                <el-form-item label="总求购箱量" prop="totalInventory">
                    <el-input v-model="totalInventory" placeholder="请输入"  style="width: 300px;" disabled>
                        <template #append>个</template>
                    </el-input>
                </el-form-item>
                <!-- <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" maxlength="500" placeholder="请输入" show-word-limit style="width: 600px;"></el-input>
                </el-form-item> -->
            </el-card>
            <el-card class="marginTop20">
                <span class="_before">发布人</span>
                <el-form-item label="求购箱人" prop="nickname" label-position="left" class="marginTop30">
                    <el-input v-model="form.nickname" disabled  placeholder="请输入" style="width: 200px;"></el-input>
                </el-form-item>
            </el-card>
            <el-card class="marginTop20">
                <span class="_before">图文描述</span>
                <el-form-item label="主图" class="marginTop30" prop="showMainImgList">
                    <el-row>
                        <el-col :span="24">
                            <upload-Img ref="uploadImgRef" :urlList="form.showMainImgList" :disabledUpload="isInfo" @uploadSccess="uploadMainSccess" @uploadRemoveSccess="uploadRemoveMainImgSccess"  />
                        </el-col>
                        <el-col :span="24" style="color: #999; font-size: 12px;" v-if="!isInfo">请上传1:1主图，主图大小不能超过3M，建议图片像素高于700*700px</el-col>
                    </el-row>
                </el-form-item>
                <el-form-item class="marginTop30">
                    <el-row style="width: 80%;">
                        <el-col :span="2" style="font-weight: 500;">详情描述</el-col> 
                        <!-- <el-col :span="15" style="color: #999;font-size: 12px;">您只需要维护一份出租箱描述数据，将同时在电脑端和手机端生效，无需分开维护</el-col> -->
                        <!-- <el-col :span="24" style="font-weight: 500;color: #666;">手机和电脑使用同一套描述</el-col> -->
                        <el-col v-for="(mark, index) in form.marks" :key="index" :span="24" class="marginTop10">
                            <upload-Img :ref="(el) => handleSetInputMap(el, index)" :urlList="mark.imgInfo" :disabledUpload="isInfo" @uploadSccess="uploadDetailSccess($event, index)" @uploadRemoveSccess="uploadRemoveDetailImgSccess($event, index)"/>
                            <el-row>
                                <el-col :span="15">
                                    <el-input v-model="mark.textVal" placeholder="在这里介绍您的集装箱" :disabled="isInfo" type="textarea" rows="2" class="marginTop10" show-word-limit maxlength="100"/>
                                </el-col>
                                <el-col v-if="index != 0" :span="9" style="position: relative;">
                                    <el-button :icon="Delete" size="small" type="danger" @click="handleClose(index)" style="position: absolute;bottom: 0;left: 5px;"></el-button>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="24" v-if="!isInfo"><el-button :icon="Plus" type="primary" size="small" @click="handleAdd">新增描述</el-button></el-col>
                    </el-row>
                </el-form-item>
            </el-card>
        </el-form>
        <el-card class="marginTop20" v-if="!isInfo">
            <el-row justify="center">
                <el-col :span="2" align="middle"><el-button type="primary" round @click="submitPublication('released')">保存待发布</el-button></el-col>
                <el-col v-if="route.query.type == 'release'" :span="2" align="middle"><el-button type="warning" round @click="submitPublication('warehouse')">放入仓库</el-button></el-col>
                <el-col v-else :span="5" align="middle" ><el-icon style="color: #46c906;"><CircleCheckFilled /></el-icon><span>最后保存于{{formatDate(form.updateTime)}}</span></el-col>
                <el-col :span="2" align="middle"><el-button type="success" round @click="submitPublication('submit')">立即发布</el-button></el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { onActivated, reactive, ref, computed, onMounted } from 'vue'
import {formatDate} from '@/utils'
import citySelect from '@/components/citySelect'
import boxPriceList from '@/views/components/boxPriceList'
import uploadImg from '@/components/upload/img.vue'
import Cookies from "js-cookie";
import { wangBuyTobeReleased, wangBuySubmit, wangBuyInWarehouse,getSaleBoxSelectDetail } from '@/api/boxDeal/boxSeel'
import orderInfo from '@/store/modules/order'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter} from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue'
const route = useRoute()
const router = useRouter()

const formRef = ref(null); // 获取表单引用

const form = reactive({
    boxStartCity:[],
    boxStartCityData:{cityCName:"",id:"",countryCName:"",countryId:""},
    boxStyle:"1",
    priceList: [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }],
    payCurrency:['CNY'],
    invoiceType:['5'],
    planPickupDate:"",
    totalInventory:0,
    remark:"",
    nickname:"",
    showMainImgList:[],
    marks:[{textVal:"",imgInfo:[]}],
    isCheckCNY:true, // 可结算币种默认选中
    isCheckUSD:false,
    updateTime:'' //最后更新时间
})

const formRules = {
    boxStartCity: [{ required: true, message: '请选择购箱城市', trigger: 'blur' }],
    boxStyle: [{ required: true, message: '请选择箱型', trigger: 'blur' }],
    payCurrency: [{ required: true, message: '请选择币种', trigger: 'blur' }],
    invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'blur' }],
    planPickupDate:[
        { required: true,message: '请选择预计提箱日期', trigger: 'blur' }
    ],
    totalInventory:[{ required: true,message: '请填写求购箱量', trigger: 'blur' }],
    nickname: [{ required: true,message: '请填写求购人', trigger: 'blur' }],
    showMainImgList: [{ required: true,message: '请上传主图', trigger: 'blur' }]
}
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - (24 * 60 * 60 * 1000)
}

const startCityList = ref([])
const isInfo=ref(false)
onActivated(() => {
    const rowData = orderInfo().rowData
    if (!rowData) return
    showData(rowData)
    
    
})
const showData = async(data: any) => { // 下架之后 重新编辑时 进入
     if(data?.isInfo){
        isInfo.value=data.isInfo
    }
    if(route.query.type == "release"){
        resetState()
    }else{
        if(!data.id ) return 
        await getSaleBoxSelectDetail(data.id).then(res => {
            if(res.code != "00000")  return ElMessage.error(res.msg)
            const  resData = res.data
            startCityList.value = [{ value: resData.carryCityId, label: resData.carryCityName, countryId: resData.carryCountryId, countryCName: resData.carryCountryName }]
            form.boxStartCity.push(resData.carryCityId)
            form.payCurrency = resData.payCurrency.split(",")
            form.priceList = resData.releaseSalePriceList
            form.invoiceType = resData.invoiceType.split(",")
            form.planPickupDate = resData.planPickupDate
            form.remark = resData.remark
            form.showMainImgList = JSON.parse(resData.mainFileList)
            form.marks = JSON.parse(resData.detailFileList)
            form.updateTime = resData.updateTime
            if(route.query.type != 'release'){
                form.boxStartCityData.id = resData.carryCityId
                form.boxStartCityData.cityCName =  resData.carryCityName
                form.boxStartCityData.countryId =  resData.carryCountryId
                form.boxStartCityData.countryCName =  resData.carryCountryName
            }

        })
    }

    form.nickname = JSON.parse(Cookies.get("User-Info"))?.nickname
    
}

const resetState = ()=> {
    form.boxStartCity = []
    startCityList.value = []
    form.boxStartCityData = {cityCName:"",id:"",countryCName:"",countryId:""}
    form.boxStyle = "1"
    form.priceList = [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }]
    form.payCurrency = ['CNY']
    form.invoiceType = ['5']
    form.planPickupDate = ""
    form.totalInventory = 0
    form.remark = ""
    form.nickname = ""
    form.showMainImgList = []
    form.marks = [{textVal:"",imgInfo:[]}]
}

//上传成功的 
const uploadMainSccess = (data: any) => {
    form.showMainImgList.push(data)
}
//img删除成功
const uploadRemoveMainImgSccess = (data: any) => {
  let index = form.showMainImgList.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index != -1) {
    form.showMainImgList.splice(index, 1)
  }
}

const uploadRef = {}
const handleSetInputMap = (el, index: number) => {
  if (el) {
    uploadRef[`imgRef${index}`] = el;
  }
};
const uploadDetailSccess = (data: any, index: number) => {
  let mark = form.marks[index]
  mark.imgInfo.push(data)
}

const uploadRemoveDetailImgSccess = (data: any, index: number) => {
  let mark = form.marks[index]
  let index1 = mark.imgInfo.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index1 != -1) {
    mark.imgInfo.splice(index1, 1)
  }
  if (mark.imgInfo.length == 0 && !mark.textVal) {
    form.marks.splice(index, 1)
  }
}

const handleClose = (val: any) => {
  form.marks.splice(val, 1)
}
const handleAdd = (val: any) => {
  form.marks.push({ textVal: "", imgInfo:[]})
}

//总库存
const totalInventory = computed(() => {
  let num = 0
  if (form.priceList && form.priceList.length > 0) {
    num = form.priceList.reduce((pre, cur) => {
      return pre + cur.inventory
    }, 0)
  }
  return num
})



// 获取购箱城市信息
const startCityInfo = (id: any, data: any) => {
    form.boxStartCity = id
    form.boxStartCityData = data
}

// wangBuyTobeReleased  保存待发布
// wangBuySubmit   立即发布
// wangBuyInWarehouse  放入仓库 

const boxPriceListRef = ref({ priceList: [] })
const submitPublication = (sign:string)=> {
     // 触发表单验证
    if(!formRef.value.validate()) ElMessage.warning('请检查表单信息是否填写完整')

    let reqParameters = {
        carryCityId: form.boxStartCityData.id,
        carryCityName: form.boxStartCityData.cityCName,
        carryCountryId: form.boxStartCityData.countryId,
        carryCountryName: form.boxStartCityData.countryCName,
        payCurrency:form.payCurrency.join(','),
        invoiceType:form.invoiceType.join(','),
        planPickupDate:form.planPickupDate,
        remark: form.remark,
        releaseSalePriceList: boxPriceListRef.value.getPriceList(),
        mainFileList:JSON.stringify(form.showMainImgList),
        detailFileList:JSON.stringify(form.marks),
    }
    console.log("reqParametersreqParameters",reqParameters)
    if(sign == "released"){ //保存待发布
        wangBuyTobeReleased(reqParameters).then((res: any) =>{
            ElMessage.success("保存待发布成功")
            router.push('agentBoxSeekBuy')
        })
    }else if(sign == "warehouse"){ //放入仓库
        wangBuyInWarehouse(reqParameters).then((res: any) =>{
            ElMessage.success("放入仓库成功")
            router.push('agentBoxSeekBuy')
        })
    }else if(sign == "submit"){  //立即发布
        wangBuySubmit(reqParameters).then((res: any) =>{
            ElMessage.success("立即发布成功")
            router.push('agentBoxSeekBuy')
        })
    }
}

//根据租箱规格选择的币种 筛选可结算币种
const publishCurrency = (val: any) => {
  form.payCurrency.length = 0 
  form.payCurrency.push(val)
  if(val =="CNY"){
    form.isCheckCNY = true
    form.isCheckUSD = false
  }else if(val == "USD"){
    form.isCheckCNY = false
    form.isCheckUSD = true
  }
}


</script>

<style lang="scss" scoped>
.publish-Purchase{
    padding: 20px;
    .el-form-item{
        margin-left: 50px;
    }
}

</style>